package com.mujin.keji.collectionsystem.module.outboundtask.views;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.PropertyFilter;
import com.mujin.keji.collectionsystem.Constant;
import com.mujin.keji.collectionsystem.R;
import com.mujin.keji.collectionsystem.base.BaseFragment;
import com.mujin.keji.collectionsystem.common.VisitStatusEnum;
import com.mujin.keji.collectionsystem.db.database.AppDataBase;
import com.mujin.keji.collectionsystem.db.domain.VisitApplyBean;
import com.mujin.keji.collectionsystem.dto.VisitAddressSort;
import com.mujin.keji.collectionsystem.dto.VisitNameSort;
import com.mujin.keji.collectionsystem.module.outboundtask.adapter.BoundTaskListAdapter;
import com.mujin.keji.collectionsystem.module.outboundtask.dto.BoundTaskDto;
import com.mujin.keji.collectionsystem.module.outboundtask.dto.VisitCaseDto;
import com.mujin.keji.collectionsystem.module.outboundtask.vo.ApplyCaseVo;
import com.mujin.keji.collectionsystem.module.outboundtask.vo.BeginVisitVo;
import com.mujin.keji.collectionsystem.module.outboundtask.vo.RefreshVo;
import com.mujin.keji.collectionsystem.utils.DisplayUtil;
import com.mujin.keji.collectionsystem.utils.EmptyUtils;
import com.mujin.keji.collectionsystem.utils.SPUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * 拜访fragment列表基类
 *
 * @author weishixiong
 * @Time 2018-03-21
 */

public abstract class BaseOutBoundTaskFragment extends BaseFragment implements BoundTaskListAdapter.BoundTaskListener {
    public RecyclerView rvBaseTask;
    private LinearLayoutManager linearLayoutManager;
    private VisitCaseDto visitCaseDto;
    private List<BoundTaskDto> mBoundTaskDtoList;
    private BoundTaskListAdapter adapter;
    private ApplyCaseVo applyCaseVo;


    private TextView tvTime;
    private TextView tvDistance;
    private LinearLayout llNoData;
    private SmartRefreshLayout srNoData;
    private TextView tvNoData;
    private SmartRefreshLayout refreshLayout;


    @Override
    protected void createViewModel() {

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        return super.onCreateView(inflater, container, savedInstanceState);

    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_baseoutboundtask;
    }

    @Override
    protected void initView(View view, Bundle savedInstanceState) {
        rvBaseTask = (RecyclerView) view.findViewById(R.id.rv_base_task);
        mBoundTaskDtoList = new ArrayList<>();
        initTaskListView();
        adapter = new BoundTaskListAdapter(BaseOutBoundTaskFragment.this.getActivity(), mBoundTaskDtoList, BaseOutBoundTaskFragment.this);
        rvBaseTask.setAdapter(adapter);
        tvTime = (TextView) getActivity().findViewById(R.id.tv_time);
        tvDistance = (TextView) getActivity().findViewById(R.id.tv_distance);
        srNoData = (SmartRefreshLayout) view.findViewById(R.id.sr_no_data);
        llNoData = (LinearLayout) view.findViewById(R.id.ll_no_data);
        tvNoData = (TextView) view.findViewById(R.id.tv_no_data);
        refreshLayout = (SmartRefreshLayout) view.findViewById(R.id.refreshLayout);
        srNoData.setEnableLoadMore(false);
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setHeaderHeight(DisplayUtil.dip2px(getActivity(), 22));
        srNoData.setHeaderHeight(DisplayUtil.dip2px(getActivity(), 22));

        //初始化请求接口的参数
        initVo();
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void reflesh(RefreshVo vo) {
        if (vo != null && vo.getCode() == 200) {
            refleshData();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        //rvBaseTask.scrollToPosition(currentPosition);
    }

    /**
     * 刷新数据
     */
    public void refleshData() {

        refreshLayout.autoRefresh();
        srNoData.autoRefresh();
        loadData();

    }

    /**
     * 初始化请求参数
     */
    private void initVo() {
        applyCaseVo = new ApplyCaseVo();
        applyCaseVo.setTimeSort(2);
    }

    /**
     * 加载数据
     */
    public void loadData() {
        applyCaseVo.setStatus(getStatus());
        //实时 获取输入框的 关键字
//        EditText editText = (EditText) (getActivity().findViewById(R.id.et_name));
//        applyCaseVo.setVisitName(editText.getText().toString());
        initBoundTaskDtoData(applyCaseVo);

    }

    private int oneCount;
    private int twoCount;
    private int threeCount;


    /**
     * 获取拜访任务列表数据
     *
     * @param vo
     */
    public void initBoundTaskDtoData(final ApplyCaseVo vo) {
        String status = VisitStatusEnum.getCodeByStatus(vo.getStatus());
        String userName = SPUtil.getData(Constant.SP.SP, Constant.SP.USER, String.class, null);
        int orderBy = ((OutBoundtaskListActivity) getActivity()).getOrderBy();
        Flowable<List<VisitApplyBean>> flowable = null;
//        if (orderBy == 0) {
//            Log.e(TAG, "initBoundTaskDtoData: 地址降序" );
            flowable = AppDataBase.getInstance(getActivity()).getVisitDao().queryVisitListByStatus(status, userName);
//        }
//        if (orderBy == 1) {
//            Log.e(TAG, "initBoundTaskDtoData: 地址升序" );
//            flowable = AppDataBase.getInstance(getActivity()).getVisitDao().queryVisitListByStatusOrderByAdressDESC(status, userName);
//        }
//        if (orderBy == 2) {
//            Log.e(TAG, "initBoundTaskDtoData: 姓名降序" );
//            flowable = AppDataBase.getInstance(getActivity()).getVisitDao().queryVisitListByStatusOrderByAdressNameASC(status, userName);
//        }
//        if (orderBy == 3) {
//            Log.e(TAG, "initBoundTaskDtoData: 姓名升序" );
//            flowable = AppDataBase.getInstance(getActivity()).getVisitDao().queryVisitListByStatusOrderByAdressNameDESC(status, userName);
//        }

        //SQLite直接获取数据

        flowable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<List<VisitApplyBean>>() {
                    @Override
                    public void onSubscribe(Subscription s) {
                        s.request(1);
                    }

                    @Override
                    public void onNext(List<VisitApplyBean> visitCountBeans) {

                        refreshLayout.finishRefresh();
                        srNoData.finishRefresh();

                        if (EmptyUtils.isNotEmpty(visitCountBeans)) {
                            //java排序
                            if (orderBy == 0) {
                                Collections.sort(visitCountBeans, new VisitAddressSort("DESC"));
                            }
                            if (orderBy == 1) {
                                Collections.sort(visitCountBeans, new VisitAddressSort("ASC"));
                            }
                            if (orderBy == 2) {
                                Collections.sort(visitCountBeans, new VisitNameSort("DESC"));
                            }
                            if (orderBy == 3) {
                                Collections.sort(visitCountBeans, new VisitNameSort("ASC"));
                            }


                            llNoData.setVisibility(View.GONE);
                            refreshLayout.setVisibility(View.VISIBLE);
                            List<BoundTaskDto> lists = new ArrayList<>();
                            for (VisitApplyBean visitApplyBean : visitCountBeans) {
                                PropertyFilter profilter = new PropertyFilter() {
                                    public boolean apply(Object object, String name, Object value) {
                                        if (name.equalsIgnoreCase("status")) {
                                            //false表示last字段将被排除在外
                                            return false;
                                        }
                                        return true;
                                    }
                                };
                                String json = JSONObject.toJSONString(visitApplyBean, profilter);
                                BoundTaskDto boundTaskDto = JSONObject.parseObject(json, BoundTaskDto.class);
                                boundTaskDto.setStatus(VisitStatusEnum.getStatusByCode(visitApplyBean.getStatus()));
                                boundTaskDto.setId(visitApplyBean.getVisitApplyId());
                                boundTaskDto.setTaskId(visitApplyBean.getTaskId());
                                lists.add(boundTaskDto);
                            }
                            mBoundTaskDtoList.clear();
                            mBoundTaskDtoList.addAll(lists);
                            adapter.notifyDataSetChanged();
                           // rvBaseTask.scrollToPosition(0);
                            //等待外访
                            if (getStatus() == 1) {
                                oneCount = mBoundTaskDtoList.size();
                                ((OutBoundtaskListActivity) getActivity()).getmStatusCountDtos().get(0).setCount(oneCount);
                                ((OutBoundtaskListActivity) getActivity()).getTripStatusAdapter().notifyDataSetChanged();
                            }
                            if (getStatus() == 2) {
                                twoCount = mBoundTaskDtoList.size();

                                ((OutBoundtaskListActivity) getActivity()).getmStatusCountDtos().get(1).setCount(twoCount);
                                ((OutBoundtaskListActivity) getActivity()).getTripStatusAdapter().notifyDataSetChanged();
                            }
                            if (getStatus() == 3) {
                                threeCount = mBoundTaskDtoList.size();
                                ((OutBoundtaskListActivity) getActivity()).getmStatusCountDtos().get(2).setCount(threeCount);
                                ((OutBoundtaskListActivity) getActivity()).getTripStatusAdapter().notifyDataSetChanged();
                            }


                            Log.e(TAG, "onNext: -----" + getStatus());
                            Log.e(TAG, "onNext: " + oneCount);
                            Log.e(TAG, "onNext: ------" + getStatus());
                            Log.e(TAG, "onNext: " + twoCount);
                            Log.e(TAG, "onNext: ------" + getStatus());
                            Log.e(TAG, "onNext: " + threeCount);


                        } else {

                            mBoundTaskDtoList.clear();
                            llNoData.setVisibility(View.VISIBLE);
                            refreshLayout.setVisibility(View.GONE);
                            adapter.notifyDataSetChanged();
                            tvNoData.setText("暂无外访任务");
                            //等待外访
                            if (getStatus() == 1) {
                                oneCount = mBoundTaskDtoList.size();
                                ((OutBoundtaskListActivity) getActivity()).getmStatusCountDtos().get(0).setCount(0);
                                ((OutBoundtaskListActivity) getActivity()).getTripStatusAdapter().notifyDataSetChanged();
                            }
                            if (getStatus() == 2) {
                                twoCount = mBoundTaskDtoList.size();
                                ((OutBoundtaskListActivity) getActivity()).getmStatusCountDtos().get(1).setCount(0);
                                ((OutBoundtaskListActivity) getActivity()).getTripStatusAdapter().notifyDataSetChanged();
                            }
                            if (getStatus() == 3) {
                                threeCount = mBoundTaskDtoList.size();
                                ((OutBoundtaskListActivity) getActivity()).getmStatusCountDtos().get(2).setCount(0);
                                ((OutBoundtaskListActivity) getActivity()).getTripStatusAdapter().notifyDataSetChanged();
                            }


                        }

                    }

                    @Override
                    public void onError(Throwable t) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 初始化拜访任务列表view
     */
    private void initTaskListView() {
        linearLayoutManager = new LinearLayoutManager(getActivity());
        rvBaseTask.setLayoutManager(linearLayoutManager);
    }

    @Override
    protected void initData() {
        visitCaseDto = new VisitCaseDto();
        refleshData();
    }

    @Override
    protected void initListener() {
        refreshLayout.setOnRefreshListener(refreshLayout -> {
            refleshData();
        });
        srNoData.setOnRefreshListener(refreshLayout1 -> {
            refleshData();
        });


    }

    abstract Integer getStatus();

    /**
     * 跳转到案件详情
     *
     * @param dto
     */
    @Override
    public void toCaseInformation(BoundTaskDto dto,int position) {
        this.currentPosition = position;
        dto.setStatus(getStatus());
        visitCaseDto.setVisitApplyId(String.valueOf(dto.getId()));
        visitCaseDto.setName(dto.getVisitName());
        visitCaseDto.setTaskTime(dto.getAllotTime());
        visitCaseDto.setVisitAddress(dto.getVisitAddress());
        visitCaseDto.setDto(dto);
        visitCaseDto.setTaskId(dto.getTaskId());
        //案件信息
        Intent intent = new Intent(getActivity(), CaseInformationActivity.class);
        intent.putExtra("visitCaseDto", visitCaseDto);
        intent.putExtra("loacationAdress", ((OutBoundtaskListActivity) getActivity()).getLoacationAdress());
        startActivity(intent);
    }
    private int currentPosition;
    /**
     * 开始外访
     *
     * @param boundTaskDto
     */
    @Override
    public void toBoundDetail(BoundTaskDto boundTaskDto,int position) {
        this.currentPosition = position;
        boundTaskDto.setStatus(getStatus());
        showTips(boundTaskDto);

    }


    /**
     * 提示是否开始外访
     *
     * @param boundTaskDto
     */
    private void showTips(final BoundTaskDto boundTaskDto) {
        // 判断是的要提示对话框 true 是
        if (SPUtil.getData(Constant.SP.SHOW_TIP_SP, Constant.SP.SHOW_TIP, Boolean.class, true) && boundTaskDto.getStatus() == 1) {
            BeginVisitVo visitVo = new BeginVisitVo();
            visitVo.setApplyId(boundTaskDto.getId());
            visitVo.setIsBegin(0);
            startToVist(boundTaskDto);

        }
        //不用提示 则 直接去外访 初始化 外访时间 和地址
        else {
            //start visit 开始外访 初始化外访时间 和地址
            startToVist(boundTaskDto);
        }


    }


    /**
     * 开始外访
     *
     * @param boundTaskDto
     */
    private void startToVist(final BoundTaskDto boundTaskDto) {
        if (1 == boundTaskDto.getStatus()) {

            BeginVisitVo visitVo = new BeginVisitVo();
            visitVo.setApplyId(boundTaskDto.getId());
            visitVo.setIsBegin(1);
            visitVo.setLocation(((OutBoundtaskListActivity) getActivity()).getLoacationAdress());

            toVisitDetail(boundTaskDto);

        } else {
            toVisitDetail(boundTaskDto);
        }

    }

    /**
     * 进入外访界面
     *
     * @param boundTaskDto
     */
    private void toVisitDetail(BoundTaskDto boundTaskDto) {
        visitCaseDto.setVisitApplyId(boundTaskDto.getId() + "");
        visitCaseDto.setName(boundTaskDto.getVisitName());
        visitCaseDto.setTaskTime(boundTaskDto.getAllotTime());
        visitCaseDto.setVisitAddress(boundTaskDto.getVisitAddress());
        visitCaseDto.setDto(boundTaskDto);
        //拜访详情
        Intent intent = new Intent(getActivity(), BoundDetailActivity.class);
        intent.putExtra("visitCaseDto", visitCaseDto);
        startActivity(intent);
    }


}
